package db.configuration;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Observable;


/**
 *
 * @author joseluis
 */
public class FileWatcher extends Observable implements Runnable{
    private String fileName;
    private long timeLastModified;
    private long time;


    public void setTime(long time) {
		this.time = time;
	}

	public FileWatcher(String fileName,long time) throws FileNotFoundException {
        this.fileName = fileName;
        this.time = time*1000;
        setTimeLastModified(new File(fileName).lastModified());
        fileExist();
    }

    public void run(){
    	 while(true){
        	 try {
     			Thread.sleep(this.time);
     				if(fileChanged()){
     					setChanged();
                        notifyObservers();
                        setTimeLastModified(new File(fileName).lastModified());
     				 }
     		} catch (InterruptedException ex) {
     		}
        }



    }
    private void fileExist() throws FileNotFoundException {
		File file = new File(this.fileName);
		if(!file.exists()){
			throw new FileNotFoundException("Archivo no encontrado");
		}
	}

    private boolean fileChanged() {
        return timeLastModified != new File(fileName).lastModified();
    }

    public void setTimeLastModified(long timeLastModified){
        this.timeLastModified = timeLastModified;
    }

     public long getTimeLastModified(){
        return timeLastModified;
    }



}
